package com.dangdang;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.widget.ImageView;

public class AngryBirdClickActivity extends Activity {

	public static final int MENU_ABOUT = Menu.FIRST;

	private BirdPaintingView mBirdPainingView;

	private ProgressDialog pd; // progress Dialog

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (null != pd) {
				pd.dismiss();
			}
		}
	};

	/**
	 * Handle the onCreate function
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mBirdPainingView = new BirdPaintingView(this);
		setContentView(mBirdPainingView);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.item1:

			// save the canvas in background
			pd = ProgressDialog.show(this, null, "Saving ...", true, false);
			new Thread() {
				public void run() {
					try {
						mBirdPainingView.saveCanvas();

						handler.sendEmptyMessage(0);

					} catch (Exception e) {
					}
				}
			}.start();

			return true;

		case R.id.item2:

			// clear the picture
			mBirdPainingView.clear();
			return true;

		default:
			return super.onContextItemSelected(item);
		}
	}

	/**
	 * The main view responsible for drawing the display, handling the finger
	 * press events and creating the background thread.
	 */
	private static class BirdPaintingView extends ImageView {
		private final Paint mPaint = new Paint();

		// the positions of the birds
		private List<Point> mPositions = new ArrayList<Point>();

		// the types of the birds
		private List<Integer> birdTypes = new ArrayList<Integer>();
		private Random generator = new Random();

		private List<Bitmap> birdImages = new ArrayList<Bitmap>();

		private Bitmap mBitmap = null;
		private Canvas mCanvas = null;

		public BirdPaintingView(Context context) {
			super(context);
			setFocusable(true);

			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito1));
			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito2));
			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito3));
			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito4));
			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito5));
			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito6));
			birdImages.add(BitmapFactory.decodeResource(getResources(),
					R.drawable.pajarito7));

		}

		/**
		 * Clear the canvas picture
		 */
		public void clear() {
			mPositions.clear();
			birdTypes.clear();

			invalidate();
		}

		/*
		 * save the picture on the canvas to some external file ref:
		 * http://stackoverflow
		 * .com/questions/649154/android-bitmap-save-to-location
		 */
		public void saveCanvas() {
			String filename;
			Date date = new Date(0);
			SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
			filename = "AB" + sdf.format(date);

			try {

				String path = Environment.getExternalStorageDirectory()
						.toString();
				OutputStream fOut = null;
				File file = new File(path, "/dcim/" + filename + ".png");
				fOut = new FileOutputStream(file);

				mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
				fOut.flush();
				fOut.close();

				MediaStore.Images.Media.insertImage(this.getContext()
						.getContentResolver(), file.getAbsolutePath(), file
						.getName(), file.getName());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		/**
		 * Draw the display
		 */
		@Override
		protected void onDraw(Canvas canvas) {

			if (null == mBitmap) {
				mBitmap = Bitmap.createBitmap(getWidth(), getHeight(),
						Config.ARGB_8888);
				mCanvas = new Canvas(mBitmap);
			}
			// draw a white background
			mPaint.setColor(Color.LTGRAY);
			mPaint.setStyle(Style.FILL);
			Rect r = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());
			mCanvas.drawRect(r, mPaint);

			// draw a line of birds
			Point startPos = new Point(0, 0);
			for (Bitmap bitmap : birdImages) {

				mCanvas.drawBitmap(bitmap, startPos.x, startPos.y, mPaint);
				startPos.x += bitmap.getWidth() + 20;
			}

			if (mPositions.size() > 0) {
				int counter = 0;
				for (Point position : mPositions) {
					int birdType = birdTypes.get(counter).intValue();
					Bitmap bitmap = birdImages.get(birdType);

					mCanvas.drawBitmap(bitmap, position.x - bitmap.getWidth()
							/ 2, position.y - bitmap.getHeight() / 2, mPaint);

					counter++;
				}
			}

			// save
			canvas.drawBitmap(mBitmap, 0, 0, null);

		}

		/**
		 * Handle the finger press event by creating a new number and adding it
		 * to in the list of counters
		 */
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				Point position = new Point((int) event.getX(),
						(int) event.getY());

				// Add the position and birdType
				mPositions.add(position);
				birdTypes.add(generator.nextInt(birdImages.size()));

				// draw the bird, randomly choose and draw the birds
				invalidate();
				break;
			}
			return true;
		}

	}

}